package com.jihui.jihuipicturebackend.controller;

import com.jihui.jihuipicturebackend.annotation.CheckAuth;
import com.jihui.jihuipicturebackend.common.BaseResponse;
import com.jihui.jihuipicturebackend.common.ResultUtils;
import com.jihui.jihuipicturebackend.constant.UserConstant;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    @ApiOperation(value = "测试上传文件")
    public BaseResponse<String> uploadPicture(@RequestPart("file") MultipartFile file) {
        // 处理上传的文件
        String originalFilename = file.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);
        File tempFile = null;
        try {
            // 上传文件
            tempFile = File.createTempFile(filePath, null);
            file.transferTo(tempFile);
            cosManager.putObject(filePath, tempFile);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("上传文件失败 + {}", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("删除临时文件失败 + {}", tempFile.getAbsolutePath());
                }
            }
        }
    }

    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/download")
    @ApiOperation(value = "测试下载图片")
    public void downloadPicture(String filepath, HttpServletResponse response) {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("下载图片失败 + {}", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载图片失败");
        } finally {
            if (cosObjectInput != null) {
                try {
                    cosObjectInput.close();
                } catch (Exception e) {
                    log.error("关闭流失败 + {}", e.getMessage());
                }
            }
        }
    }
}
